package com.jingxuan.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.jingxuan.dto.response.RankingItemResponse;
import com.jingxuan.entity.Comment;
import com.jingxuan.entity.Product;
import com.jingxuan.mapper.CommentsMapper;
import com.jingxuan.mapper.ProductsMapper;
import com.jingxuan.mapper.RecommendMapper;
import com.jingxuan.mapper.RecommendMapper.ProductFeatureWithDescriptionDto;
import com.jingxuan.service.RankService;
import com.jingxuan.util.RankAlgorithm;
import com.jingxuan.util.RankAlgorithm.CommentInfo;
import com.jingxuan.util.RankAlgorithm.GoodRateInfo;
import com.jingxuan.util.RankAlgorithm.ProductFeature;
import com.jingxuan.util.RedisUtil;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 排行榜服务实现类
 */
@Slf4j
@Service
public class RankServiceImpl implements RankService, ApplicationRunner {

    @Autowired
    private RecommendMapper recommendMapper;

    @Autowired
    private CommentsMapper commentsMapper;

    @Autowired
    private ProductsMapper productsMapper;

    @Autowired
    private RedisUtil redisUtil;

    private static final String REDIS_KEY_PREFIX = "rank:features:";
    private static final long REDIS_TTL_HOURS = 24;

    @Override
    @Cacheable(value = "rankings", key = "'recommend'", unless = "#result == null || #result.size() == 0")
    public List<RankingItemResponse> getRecommendRanking(Integer limit) {
        log.info("开始计算推荐榜，limit={}", limit);

        try {
            // 获取所有商品及其描述
            List<ProductFeatureWithDescriptionDto> products = recommendMapper.getAllProductsWithDescription();
            if (CollectionUtils.isEmpty(products)) {
                return new ArrayList<>();
            }

            // 计算价格范围
            BigDecimal minPrice = products.stream()
                    .map(ProductFeatureWithDescriptionDto::getPrice)
                    .filter(Objects::nonNull)
                    .min(BigDecimal::compareTo)
                    .orElse(BigDecimal.valueOf(1)); // 避免除零

            BigDecimal maxPrice = products.stream()
                    .map(ProductFeatureWithDescriptionDto::getPrice)
                    .filter(Objects::nonNull)
                    .max(BigDecimal::compareTo)
                    .orElse(BigDecimal.valueOf(1000)); // 默认最大值

            // 如果所有价格相同，设置一个合理的范围
            if (minPrice.compareTo(maxPrice) == 0) {
                maxPrice = minPrice.add(BigDecimal.valueOf(100));
            }

            List<ScoredProduct> scoredProducts = new ArrayList<>();

            // 计算每个商品的得分
            for (ProductFeatureWithDescriptionDto product : products) {
                if (product == null || product.getProductId() == null) {
                    continue; // 跳过无效商品
                }

                try {
                    // 获取或解析特征
                    ProductFeature features = getOrParseFeatures(product);
                    if (features == null) {
                        log.warn("商品特征解析失败，跳过该商品，productId={}", product.getProductId());
                        continue;
                    }

                    // 获取评论列表
                    List<Comment> comments = null;
                    try {
                        comments = commentsMapper.selectAllCommentsByProductId(product.getProductId());
                    } catch (Exception e) {
                        log.warn("获取商品评论失败，productId={}, error={}", product.getProductId(), e.getMessage());
                        comments = new ArrayList<>();
                    }
                    List<CommentInfo> commentInfos = convertToCommentInfos(comments);

                    // 计算各维度得分
                    double priceScore = RankAlgorithm.calculatePriceScore(
                            product.getPrice(), minPrice, maxPrice);

                    double sentimentScore = RankAlgorithm.calculateSentimentScore(commentInfos);
                    double commentDetailScore = RankAlgorithm.calculateCommentDetailScore(commentInfos);
                    double infoValueScore = RankAlgorithm.calculateInformationValueScore(commentInfos);
                    double reputationScore = RankAlgorithm.calculateReputationScore(
                            features.getGoodRate() != null ? features.getGoodRate() : 0.0,
                            commentDetailScore,
                            sentimentScore,
                            infoValueScore);

                    double heatScore = RankAlgorithm.calculateHeatScore(
                            product.getCommentCount() != null ? product.getCommentCount() : 0,
                            features.getCartCount() != null ? features.getCartCount() : 0,
                            features.getReturnCustomerCount() != null ? features.getReturnCustomerCount() : 0);

                    double timelinessScore = RankAlgorithm.calculateTimelinessScore(
                            product.getLastCommentTime(),
                            LocalDateTime.now(),
                            product.getProductName(),
                            product.getDescription());

                    // 计算综合得分
                    double finalScore = RankAlgorithm.calculateRecommendScore(
                            priceScore, reputationScore, heatScore, timelinessScore);

                    scoredProducts.add(new ScoredProduct(product, finalScore));

                } catch (Exception e) {
                    log.warn("计算商品得分失败，productId={}, error={}", product.getProductId(), e.getMessage());
                }
            }

            // 按得分排序并限制数量
            List<ScoredProduct> sortedProducts = scoredProducts.stream()
                    .sorted((a, b) -> Double.compare(b.getScore(), a.getScore()))
                    .limit(limit != null ? limit : 20)
                    .collect(Collectors.toList());

            // 转换为响应DTO
            List<RankingItemResponse> result = new ArrayList<>();
            for (int i = 0; i < sortedProducts.size(); i++) {
                ScoredProduct scored = sortedProducts.get(i);
                RankingItemResponse response = convertToRankingItemResponse(scored.getProduct(), i + 1,
                        scored.getScore());
                result.add(response);
            }

            log.info("推荐榜计算完成，返回{}条数据", result.size());
            return result;

        } catch (Exception e) {
            log.error("计算推荐榜失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    @Cacheable(value = "rankings", key = "'value'", unless = "#result == null || #result.size() == 0")
    public List<RankingItemResponse> getValueRanking(Integer limit) {
        log.info("开始计算性价比榜，limit={}", limit);

        try {
            // 获取所有商品及其描述
            List<ProductFeatureWithDescriptionDto> products = recommendMapper.getAllProductsWithDescription();
            if (CollectionUtils.isEmpty(products)) {
                return new ArrayList<>();
            }

            List<ScoredProduct> scoredProducts = new ArrayList<>();

            // 计算每个商品的性价比得分
            for (ProductFeatureWithDescriptionDto product : products) {
                if (product == null || product.getProductId() == null) {
                    continue; // 跳过无效商品
                }

                try {
                    // 获取或解析特征
                    ProductFeature features = getOrParseFeatures(product);
                    if (features == null) {
                        log.warn("商品特征解析失败，跳过该商品，productId={}", product.getProductId());
                        continue;
                    }

                    // 获取评论列表
                    List<Comment> comments = null;
                    try {
                        comments = commentsMapper.selectAllCommentsByProductId(product.getProductId());
                    } catch (Exception e) {
                        log.warn("获取商品评论失败，productId={}, error={}", product.getProductId(), e.getMessage());
                        comments = new ArrayList<>();
                    }
                    List<CommentInfo> commentInfos = convertToCommentInfos(comments);

                    // 计算口碑得分（用于质量分）
                    double sentimentScore = RankAlgorithm.calculateSentimentScore(commentInfos);
                    double commentDetailScore = RankAlgorithm.calculateCommentDetailScore(commentInfos);
                    double infoValueScore = RankAlgorithm.calculateInformationValueScore(commentInfos);
                    double reputationScore = RankAlgorithm.calculateReputationScore(
                            features.getGoodRate() != null ? features.getGoodRate() : 0.0,
                            commentDetailScore,
                            sentimentScore,
                            infoValueScore);

                    // 计算品牌信誉分
                    double brandScore = RankAlgorithm.calculateBrandScore(product.getProductName());

                    // 计算质量分
                    double qualityScore = RankAlgorithm.calculateQualityScore(reputationScore, brandScore);

                    // 计算基础性价比
                    double baseValueScore = RankAlgorithm.calculateBaseValueScore(
                            qualityScore, product.getPrice());

                    // 计算价值验证分
                    double valueVerificationScore = RankAlgorithm.calculateValueVerificationScore(
                            commentInfos,
                            features.getReturnCustomerCount() != null ? features.getReturnCustomerCount() : 0,
                            features.getCartCount() != null ? features.getCartCount() : 0);

                    // 计算最终性价比得分
                    double finalScore = RankAlgorithm.calculateFinalValueScore(
                            baseValueScore, valueVerificationScore);

                    // 价格门槛：口碑评分必须≥40分（降低门槛，确保有数据展示）
                    // 如果最终得分有效（>0），则加入排行榜
                    if (reputationScore >= 40 && finalScore > 0) {
                        scoredProducts.add(new ScoredProduct(product, finalScore));
                    } else {
                        log.debug("商品未满足性价比榜门槛，productId={}, reputationScore={}, finalScore={}",
                                product.getProductId(), reputationScore, finalScore);
                    }

                } catch (Exception e) {
                    log.warn("计算商品性价比得分失败，productId={}, error={}", product.getProductId(), e.getMessage());
                }
            }

            // 按得分排序并限制数量
            List<ScoredProduct> sortedProducts = scoredProducts.stream()
                    .sorted((a, b) -> Double.compare(b.getScore(), a.getScore()))
                    .limit(limit != null ? limit : 3)
                    .collect(Collectors.toList());

            // 如果仍然没有数据，进一步降低门槛（移除口碑评分限制，只要求有有效价格和得分）
            if (sortedProducts.isEmpty() && !products.isEmpty()) {
                log.warn("性价比榜无数据，降低门槛重新计算");
                scoredProducts.clear();

                for (ProductFeatureWithDescriptionDto product : products) {
                    if (product == null || product.getProductId() == null) {
                        continue;
                    }

                    try {
                        ProductFeature features = getOrParseFeatures(product);
                        if (features == null) {
                            continue;
                        }

                        List<Comment> comments = null;
                        try {
                            comments = commentsMapper.selectAllCommentsByProductId(product.getProductId());
                        } catch (Exception e) {
                            comments = new ArrayList<>();
                        }
                        List<CommentInfo> commentInfos = convertToCommentInfos(comments);

                        double sentimentScore = RankAlgorithm.calculateSentimentScore(commentInfos);
                        double commentDetailScore = RankAlgorithm.calculateCommentDetailScore(commentInfos);
                        double infoValueScore = RankAlgorithm.calculateInformationValueScore(commentInfos);
                        double reputationScore = RankAlgorithm.calculateReputationScore(
                                features.getGoodRate() != null ? features.getGoodRate() : 0.0,
                                commentDetailScore,
                                sentimentScore,
                                infoValueScore);

                        double brandScore = RankAlgorithm.calculateBrandScore(product.getProductName());
                        double qualityScore = RankAlgorithm.calculateQualityScore(reputationScore, brandScore);
                        double baseValueScore = RankAlgorithm.calculateBaseValueScore(
                                qualityScore, product.getPrice());
                        double valueVerificationScore = RankAlgorithm.calculateValueVerificationScore(
                                commentInfos,
                                features.getReturnCustomerCount() != null ? features.getReturnCustomerCount() : 0,
                                features.getCartCount() != null ? features.getCartCount() : 0);
                        double finalScore = RankAlgorithm.calculateFinalValueScore(
                                baseValueScore, valueVerificationScore);

                        // 降低门槛：只要价格有效且有得分就加入
                        if (product.getPrice() != null && product.getPrice().doubleValue() > 0 && finalScore > 0) {
                            scoredProducts.add(new ScoredProduct(product, finalScore));
                        }
                    } catch (Exception e) {
                        // 忽略单个商品错误
                    }
                }

                sortedProducts = scoredProducts.stream()
                        .sorted((a, b) -> Double.compare(b.getScore(), a.getScore()))
                        .limit(limit != null ? limit : 3)
                        .collect(Collectors.toList());
            }

            // 转换为响应DTO
            List<RankingItemResponse> result = new ArrayList<>();
            for (int i = 0; i < sortedProducts.size(); i++) {
                ScoredProduct scored = sortedProducts.get(i);
                RankingItemResponse response = convertToRankingItemResponse(scored.getProduct(), i + 1,
                        scored.getScore());
                result.add(response);
            }

            log.info("性价比榜计算完成，返回{}条数据", result.size());
            return result;

        } catch (Exception e) {
            log.error("计算性价比榜失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    @Cacheable(value = "rankings", key = "'new'", unless = "#result == null || #result.size() == 0")
    public List<RankingItemResponse> getNewProductRanking(Integer limit) {
        log.info("开始计算新品榜，limit={}", limit);

        try {
            // 获取所有商品及其描述
            List<ProductFeatureWithDescriptionDto> products = recommendMapper.getAllProductsWithDescription();
            if (CollectionUtils.isEmpty(products)) {
                return new ArrayList<>();
            }

            List<ScoredProduct> scoredProducts = new ArrayList<>();

            // 计算每个商品的热力值
            for (ProductFeatureWithDescriptionDto product : products) {
                if (product == null || product.getProductId() == null) {
                    continue; // 跳过无效商品
                }

                try {
                    // 获取或解析特征
                    ProductFeature features = getOrParseFeatures(product);
                    if (features == null) {
                        log.warn("商品特征解析失败，跳过该商品，productId={}", product.getProductId());
                        continue;
                    }

                    // 获取评论列表
                    List<Comment> comments = null;
                    try {
                        comments = commentsMapper.selectAllCommentsByProductId(product.getProductId());
                    } catch (Exception e) {
                        log.warn("获取商品评论失败，productId={}, error={}", product.getProductId(), e.getMessage());
                        comments = new ArrayList<>();
                    }
                    List<CommentInfo> commentInfos = convertToCommentInfos(comments);

                    // 计算新品识别分
                    double newProductScore = RankAlgorithm.calculateNewProductScore(
                            commentInfos,
                            LocalDateTime.now(),
                            product.getProductName(),
                            product.getDescription());

                    // 计算热力增长分
                    double heatGrowthScore = RankAlgorithm.calculateHeatGrowthScore(
                            commentInfos,
                            LocalDateTime.now(),
                            features.getCartCount() != null ? features.getCartCount() : 0,
                            product.getPrice());

                    // 计算口碑得分（用于质量基础分）
                    double sentimentScore = RankAlgorithm.calculateSentimentScore(commentInfos);
                    double commentDetailScore = RankAlgorithm.calculateCommentDetailScore(commentInfos);
                    double infoValueScore = RankAlgorithm.calculateInformationValueScore(commentInfos);
                    double reputationScore = RankAlgorithm.calculateReputationScore(
                            features.getGoodRate() != null ? features.getGoodRate() : 0.0,
                            commentDetailScore,
                            sentimentScore,
                            infoValueScore);

                    // 计算质量基础分
                    double qualityBaseScore = RankAlgorithm.calculateQualityBaseScore(
                            reputationScore,
                            product.getCommentCount() != null ? product.getCommentCount() : 0,
                            product.getDescription());

                    // 计算最终热力值
                    double finalHeatValue = RankAlgorithm.calculateFinalHeatValue(
                            newProductScore,
                            heatGrowthScore,
                            qualityBaseScore,
                            product.getCommentCount() != null ? product.getCommentCount() : 0);

                    scoredProducts.add(new ScoredProduct(product, finalHeatValue));

                } catch (Exception e) {
                    log.warn("计算商品热力值失败，productId={}, error={}", product.getProductId(), e.getMessage());
                }
            }

            // 按得分排序并限制数量
            List<ScoredProduct> sortedProducts = scoredProducts.stream()
                    .sorted((a, b) -> Double.compare(b.getScore(), a.getScore()))
                    .limit(limit != null ? limit : 3)
                    .collect(Collectors.toList());

            // 转换为响应DTO
            List<RankingItemResponse> result = new ArrayList<>();
            for (int i = 0; i < sortedProducts.size(); i++) {
                ScoredProduct scored = sortedProducts.get(i);
                RankingItemResponse response = convertToRankingItemResponse(scored.getProduct(), i + 1,
                        scored.getScore());
                result.add(response);
            }

            log.info("新品榜计算完成，返回{}条数据", result.size());
            return result;

        } catch (Exception e) {
            log.error("计算新品榜失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public void parseAndCacheFeatures(String productId) {
        log.info("开始解析并缓存商品特征，productId={}", productId);

        try {
            // 获取商品描述
            String description = recommendMapper.getProductDescription(productId);
            if (description == null || description.isEmpty()) {
                log.warn("商品描述为空，productId={}", productId);
                return;
            }

            // 解析特征
            GoodRateInfo goodRateInfo = RankAlgorithm.parseGoodRate(description);
            Integer cartCount = RankAlgorithm.parseCartCount(description);
            Integer returnCustomerCount = RankAlgorithm.parseReturnCustomerCount(description);
            // 发货速度和客服响应时间暂不存储，仅解析以备后续使用
            RankAlgorithm.parseDeliverySpeed(description);
            RankAlgorithm.parseServiceResponseTime(description);

            // 构建特征对象
            ProductFeature features = ProductFeature.builder()
                    .productId(productId)
                    .goodRate(goodRateInfo.getGoodRate())
                    .cartCount(cartCount)
                    .returnCustomerCount(returnCustomerCount)
                    .build();

            // 存储到Redis
            String redisKey = REDIS_KEY_PREFIX + productId;
            redisUtil.set(redisKey, features, REDIS_TTL_HOURS, java.util.concurrent.TimeUnit.HOURS);

            log.info("商品特征解析并缓存完成，productId={}", productId);

        } catch (Exception e) {
            log.error("解析并缓存商品特征失败，productId={}", productId, e);
        }
    }

    /**
     * 获取或解析商品特征（优先从Redis获取）
     */
    private ProductFeature getOrParseFeatures(ProductFeatureWithDescriptionDto product) {
        String redisKey = REDIS_KEY_PREFIX + product.getProductId();

        // 尝试从Redis获取
        try {
            Object cached = redisUtil.get(redisKey);
            if (cached != null) {
                // 处理Redis反序列化后的对象
                if (cached instanceof ProductFeature) {
                    ProductFeature features = (ProductFeature) cached;
                    // 验证数据完整性
                    if (features.getProductId() != null) {
                        return features;
                    }
                } else if (cached instanceof java.util.Map) {
                    // Redis可能返回Map类型，需要转换
                    @SuppressWarnings("unchecked")
                    java.util.Map<String, Object> map = (java.util.Map<String, Object>) cached;
                    ProductFeature features = convertMapToProductFeatures(map, product);
                    if (features != null) {
                        return features;
                    }
                }
            }
        } catch (Exception e) {
            log.warn("从Redis获取商品特征失败，将重新解析，productId={}, error={}",
                    product.getProductId(), e.getMessage());
        }

        // Redis中没有或获取失败，解析并缓存
        ProductFeature features = parseFeaturesFromProduct(product);

        // 缓存到Redis（异步，避免阻塞）
        try {
            redisUtil.set(redisKey, features, REDIS_TTL_HOURS, java.util.concurrent.TimeUnit.HOURS);
        } catch (Exception e) {
            log.warn("缓存商品特征到Redis失败，productId={}, error={}",
                    product.getProductId(), e.getMessage());
        }

        return features;
    }

    /**
     * 从商品信息解析特征
     */
    private ProductFeature parseFeaturesFromProduct(ProductFeatureWithDescriptionDto product) {
        if (product.getDescription() != null && !product.getDescription().isEmpty()) {
            GoodRateInfo goodRateInfo = RankAlgorithm.parseGoodRate(product.getDescription());
            Integer cartCount = RankAlgorithm.parseCartCount(product.getDescription());
            Integer returnCustomerCount = RankAlgorithm.parseReturnCustomerCount(product.getDescription());

            return ProductFeature.builder()
                    .productId(product.getProductId())
                    .productName(product.getProductName())
                    .price(product.getPrice())
                    .description(product.getDescription())
                    .goodRate(goodRateInfo.getGoodRate() != null ? goodRateInfo.getGoodRate() / 100.0
                            : (product.getPositiveRate() != null ? product.getPositiveRate() : 0.0))
                    .cartCount(cartCount != null ? cartCount : 0)
                    .returnCustomerCount(returnCustomerCount != null ? returnCustomerCount : 0)
                    .build();
        }

        // 没有描述，返回默认特征
        return ProductFeature.builder()
                .productId(product.getProductId())
                .productName(product.getProductName())
                .price(product.getPrice())
                .goodRate(product.getPositiveRate() != null ? product.getPositiveRate() : 0.0)
                .cartCount(0)
                .returnCustomerCount(0)
                .build();
    }

    /**
     * 将Map转换为ProductFeatures（处理Redis反序列化问题）
     */
    private ProductFeature convertMapToProductFeatures(java.util.Map<String, Object> map,
            ProductFeatureWithDescriptionDto product) {
        try {
            ProductFeature.ProductFeatureBuilder builder = ProductFeature.builder();

            if (map.containsKey("productId")) {
                builder.productId(String.valueOf(map.get("productId")));
            } else {
                builder.productId(product.getProductId());
            }

            if (map.containsKey("productName")) {
                builder.productName(String.valueOf(map.get("productName")));
            } else {
                builder.productName(product.getProductName());
            }

            if (map.containsKey("price")) {
                Object priceObj = map.get("price");
                if (priceObj instanceof BigDecimal) {
                    builder.price((BigDecimal) priceObj);
                } else if (priceObj instanceof Number) {
                    builder.price(BigDecimal.valueOf(((Number) priceObj).doubleValue()));
                } else {
                    builder.price(product.getPrice());
                }
            } else {
                builder.price(product.getPrice());
            }

            if (map.containsKey("description")) {
                builder.description(String.valueOf(map.get("description")));
            } else {
                builder.description(product.getDescription());
            }

            if (map.containsKey("goodRate")) {
                Object rateObj = map.get("goodRate");
                if (rateObj instanceof Number) {
                    builder.goodRate(((Number) rateObj).doubleValue());
                } else {
                    builder.goodRate(product.getPositiveRate() != null ? product.getPositiveRate() : 0.0);
                }
            } else {
                builder.goodRate(product.getPositiveRate() != null ? product.getPositiveRate() : 0.0);
            }

            if (map.containsKey("cartCount")) {
                Object cartObj = map.get("cartCount");
                if (cartObj instanceof Number) {
                    builder.cartCount(((Number) cartObj).intValue());
                } else {
                    builder.cartCount(0);
                }
            } else {
                builder.cartCount(0);
            }

            if (map.containsKey("returnCustomerCount")) {
                Object returnObj = map.get("returnCustomerCount");
                if (returnObj instanceof Number) {
                    builder.returnCustomerCount(((Number) returnObj).intValue());
                } else {
                    builder.returnCustomerCount(0);
                }
            } else {
                builder.returnCustomerCount(0);
            }

            return builder.build();
        } catch (Exception e) {
            log.warn("转换Map到ProductFeatures失败，将使用默认值，error={}", e.getMessage());
            return null;
        }
    }

    /**
     * 转换Comment为CommentInfo
     */
    private List<CommentInfo> convertToCommentInfos(List<Comment> comments) {
        if (CollectionUtils.isEmpty(comments)) {
            return new ArrayList<>();
        }

        return comments.stream()
                .map(comment -> CommentInfo.builder()
                        .content(comment.getContent())
                        .publishDate(comment.getPublishDate())
                        .likeCount(comment.getLikeCount())
                        .build())
                .collect(Collectors.toList());
    }

    /**
     * 转换为RankingItemResponse
     */
    private RankingItemResponse convertToRankingItemResponse(ProductFeatureWithDescriptionDto product,
            int rank, double score) {
        RankingItemResponse response = new RankingItemResponse();
        response.setRank(rank);
        response.setProductId(product != null ? product.getProductId() : null);
        response.setProductName(product != null ? product.getProductName() : "");
        response.setPrice(product != null ? product.getPrice() : BigDecimal.ZERO);
        response.setImageUrl(product != null ? product.getPictureUrl() : "");
        response.setPlatformName(product != null ? product.getPlatformName() : "");
        response.setScore(score);

        // 获取商品链接
        try {
            if (product != null && product.getProductId() != null) {
                Product productEntity = productsMapper.selectById(product.getProductId());
                if (productEntity != null) {
                    response.setProductUrl(productEntity.getLink());
                    response.setApplauseRate(productEntity.getApplauseRate());
                }
            }
        } catch (Exception e) {
            log.warn("获取商品详情失败，productId={}, error={}",
                    product != null ? product.getProductId() : null, e.getMessage());
        }

        return response;
    }

    /**
     * 得分商品内部类
     */
    @Data
    private static class ScoredProduct {
        private ProductFeatureWithDescriptionDto product;
        private double score;

        public ScoredProduct(ProductFeatureWithDescriptionDto product, double score) {
            this.product = product;
            this.score = score;
        }
    }

    @Autowired
    @Lazy
    private RankService self;

    @Override
    @Scheduled(cron = "0 0 4 * * ?")
    public void refreshAllRankings() {
        log.info("开始刷新所有榜单缓存");
        // 1. 清除所有缓存
        self.clearAllRankings();

        // 2. 重新触发计算并缓存 (通过调用代理对象的接口方法)
        // 由于缓存已被清除，这些调用会执行实际逻辑并将结果放入缓存
        self.getRecommendRanking(20);
        self.getValueRanking(20);
        self.getNewProductRanking(20);

        log.info("所有榜单缓存刷新完成");
    }

    @Override
    @CacheEvict(value = "rankings", allEntries = true)
    public void clearAllRankings() {
        log.info("清空所有榜单缓存");
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("应用启动，开始初始化排行榜数据...");
        this.refreshAllRankings();
    }
}
